﻿namespace SharePointCSVImporter
{
    using System.IO;
    using System.Windows.Controls;

    using Newtonsoft.Json;

    public class ConfigurationImportExporter
    {
        #region Methods

        public static void ExportConfiguration(Configuration config)
        {
            if (config != null)
            {
                if (config.FieldMappings != null)
                {
                    string text = JsonConvert.SerializeObject(config);
                    if (!string.IsNullOrEmpty(text))
                    {
                        SaveFileDialog sfd = new SaveFileDialog();
                        sfd.Filter = "(*.txt)|*.txt|All Files(*.*)|*.*";
                        sfd.DefaultExt = "txt";
                        sfd.DefaultFileName = "SharePointCSVImportMapping.txt";
                        if (sfd.ShowDialog().Value)
                        {
                            using (StreamWriter sw = new StreamWriter(sfd.OpenFile()))
                            {
                                sw.Write(text);
                                sw.AutoFlush = true;
                                sw.Flush();
                            }
                        }
                    }
                }

            }
        }

        public Configuration ImportConfiguration()
        {
            Configuration rvalue = null;

            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Multiselect = false;
            dlg.Filter = "(*.txt)|*.txt|All Files(*.*)|*.*";
            bool? retval = dlg.ShowDialog();

            if (retval != null && retval == true)
            {
                if (dlg.File != null)
                {

                    using (var file = dlg.File.OpenText())
                    {
                        string text = file.ReadToEnd();
                        if (!string.IsNullOrEmpty(text))
                        {
                            try
                            {
                                rvalue = JsonConvert.DeserializeObject<Configuration>(text);
                            }
                            catch
                            {

                            }
                        }
                    }

                }

            }

            return rvalue;
        }

        #endregion Methods
    }
}